/*
 RLRecyclingLogViewController.m
 Date Created: February 18, 2010
 
 Author: Karol Krizka <kkrizka@gmail.com>
 
 Copyright (C) 2010 Green-Power
 
 URL: http://code.google.com/p/green-power
 
 This program is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; either version 3 of the License, or
 (at your option) any later version.
 
 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 
 $Id$
 */

#import "RLRecyclingLogViewController.h"

#import "RLStyleFormatter.h"
#import "RLRecyclingRunViewController.h"
#import "RLEditRecyclingRunViewController.h"

@implementation RLRecyclingLogViewController

@synthesize log;
@synthesize thisMonthTotalLabel;
@synthesize lastMonthTotalLabel;
@synthesize logTableViewController;

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
  [super viewDidLoad];
	[self setTitle:@"Recycling Log"];
  
  // Make sure the back button displayed will say "Back"
  self.navigationItem.backBarButtonItem=[[UIBarButtonItem alloc] initWithTitle:@"Back"
                                                                         style:UIBarButtonItemStylePlain
                                                                        target:nil 
                                                                        action:nil];
  [self.navigationItem.backBarButtonItem release];

  self.logTableViewController.log=self.log;
  
  [self updateTotalLabels];
}

- (void)setLog:(RLRecyclingLog *)logArg {
  if(!log) { // Unregeister previous logs
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:NSManagedObjectContextDidSaveNotification
                                                  object:log.managedObjectContext];
  }
  log=logArg;
  self.logTableViewController.log=logArg;
  
  [[NSNotificationCenter defaultCenter] addObserver:self
                                           selector:@selector(updateRunsOnLogSave:)
                                               name:NSManagedObjectContextDidSaveNotification
                                             object:log.managedObjectContext];
  
  [self updateTotalLabels];
  [(UITableView *)logTableViewController.view reloadData];
}

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}

- (void)updateTotalLabels {
  self.thisMonthTotalLabel.text=[RLStyleFormatter formatMonetaryValue:self.log.thisMonthTotal];
  self.lastMonthTotalLabel.text=[RLStyleFormatter formatMonetaryValue:self.log.lastMonthTotal];
}

- (void)updateRunsOnLogSave:(NSNotification *)notification {
  [(UITableView *)logTableViewController.view reloadData];
  [self updateTotalLabels];
}

- (IBAction)showAddView {
  // Create a new run and setup undo actions
  [self.log.managedObjectContext processPendingChanges];
  [self.log.managedObjectContext.undoManager beginUndoGrouping];
  RLRecyclingRun *newRun=[[self log] createRun];

  [self startEditingRun:newRun];
}

- (void)startEditingRun:(RLRecyclingRun *)run {
  // Prepare view
  RLEditRecyclingRunViewController *editRecyclingRunViewController=(RLEditRecyclingRunViewController *)[[RLEditRecyclingRunViewController alloc] initWithRun:run];
  
  // Setup responses to the buttons being clicked in the edit run view
  editRecyclingRunViewController.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSave
                                                                                                                 target:self 
                                                                                                                 action:@selector(doneEditingRun)];
  // We have to reaplce the left bar button with a custom button, because
  // the back bar button does not handle any actions. This means that 
  // we loose the arrow shape. :(
  editRecyclingRunViewController.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel
                                                                                                                target:self 
                                                                                                                action:@selector(undoEditingRun)];
  
  // Show view
  [[self navigationController] pushViewController:editRecyclingRunViewController
                                         animated:YES];
  
  // Cleanup
  [editRecyclingRunViewController.navigationItem.rightBarButtonItem release];
  [editRecyclingRunViewController.navigationItem.leftBarButtonItem release];
  [editRecyclingRunViewController release]; 
}

- (void)undoEditingRun {
  [self.log.managedObjectContext processPendingChanges];
  [self.log.managedObjectContext.undoManager endUndoGrouping]; //Undo any changes since last save
  [self.log.managedObjectContext.undoManager undoNestedGroup]; 
  [self.navigationController popViewControllerAnimated:YES];
}

- (void)doneEditingRun {
  [self.log.managedObjectContext processPendingChanges];
  [self.log.managedObjectContext.undoManager endUndoGrouping];
  
  NSError *error;
  if( ![self.log.managedObjectContext save:&error] ) {
    // TODO Handle error
    NSLog(@"Error saving run.");
  }
  [self.navigationController popViewControllerAnimated:YES];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  [tableView deselectRowAtIndexPath:indexPath animated:YES];
  RLRecyclingRun *run=[[log runsOrderedByDate:NO] objectAtIndex:indexPath.row];

  // Prepare view
  RLRecyclingRunViewController *recyclingRunViewController=[[RLRecyclingRunViewController alloc] initWithRun:run];
  
  // Show view
  [[self navigationController] pushViewController:recyclingRunViewController
                                         animated:YES];
  
  // Cleanup
  [recyclingRunViewController release]; 
}

- (void)dealloc {
    [super dealloc];
}


@end
